var wxParse = require('../../wxParse/wxParse.js');
var common = require("../../utils/Conmon.js");
var app = getApp();

var apiurl = app.globalData.apiurl;
var selectIndex = []
//var num = 1;
var Status = 0;
var PageIndex = 1;
var PageSize = 5;
var IsLastPage = false;
var RTime2;
var PageIndexTeam = 1;
var PageSizeTeam = 5;
var goodsinfoList = [];
var goodsinfo = null;
var teamselectIndex = [];

Page({
  data: {
    like: false,
    tab: [{
        id: "0",
        text: "商品详情",
        selected: true
      },
      {
        id: "1",
        text: "商品评价",
        selected: false
      },
    ],
    imgUrls: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    popin: false,
    sharepopin: false,
    selected: true,
    selected1: false,
    teamIndex: 0,
    team: [],
    morebtn: false,
    productId: 0,
    vo: [],
    specList: [],
    num: 1,
    _spechtml: "",
    goodsinfo: null,
    shopID: 0,
    CommentList: [],
    cansu: false,
    joinTeamUser: {},
    activityOverDay: "00",
    activityOverHour: "00",
    activityOverMinute: "00",
    activityOverSecond: "00",
    jointeamOverDay: "00",
    jointeamOverHour: "00",
    jointeamOverMinute: "00",
    jointeamOverSecond: "00",
    teambuypopin: false,
    teamGoodsinfoList: [],
    teamGoodsinfo: null,
    teamSpecList: [],
    _teamspechtml: "",
    teamNum: 0,
    teamBuyNum: 1,
    buyType: 0, //购买类型 0开团 1参团
    teamId: 0,
    activitytitle: "",
    activitycontent: "",
    TeamMoreList: [], //更多拼团
    hiddenMoreTeam: true,
    allTeamCount: 0,
    nocomment: true,
    MaxNum: 0
  },
  onShareAppMessage(res) {
    var that = this;
    var pic = this.data.vo.ProductInfo.ProductImg;
    var ptitle = this.data.vo.ProductInfo.ProductName;
    var price = this.data.vo.ProductInfo.CurrentPrice;
    var url = '/pages/details/details?productId=' + this.data.productId + '&shopID=' + this.data.shopID;
    return {
      title: ptitle,
      imageUrl: pic,
      path: url,
      success: function(res) {
        var data = {
          CustID: app.globalData.custID,
          UserID: wx.getStorageSync('UserInfo').UserID,
          ProductID: that.data.productId,
          Name: ptitle,
          Img: pic,
          Price: price,
          Commission: 0,
          Link: url
        };
        wx.request({
          url: app.globalData.apiurl + "/mobile/api/ShareLog/Log",
          data: JSON.stringify(data),
          method: 'POST',
          header: {
            'X_ManuName': app.globalData.manuName,
            "test": "213123"
          },
          success: function(res) {

          }
        })
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  onLoad: function(options) {
    common.pageInit(function() {});
    var shopID = 0;
    if (options.shopID > 0) {
      shopID = options.shopID;
    }
    var shareTeamId = 0;
    if (options.teamId > 0) {
      shareTeamId = options.teamId;
    }
    this.setData({
      productId: options.productId,
      shopID: shopID,
      teamId: shareTeamId
    });
    loadDetail(this);
    getMoreTeam(this);
    QueryCommentList(this);
  },
  onUnload: function() {
    console.log('离开页面');
  },
  //收藏
  changlike: function() {
    collect(this);
  },
  bindPickerChange: function(e) {
    this.setData({
      teamIndex: e.detail.value
    })


    var num = this.data.team[e.detail.value];
    this.teamNumChange(num);
  },
  //发起拼团
  initiateTeamBuy: function(e) {
    var num = e.currentTarget.id;
    this.setData({
      teamIndex: e.currentTarget.dataset.i,
      teambuypopin: !this.data.teambuypopin,
    })
    this.teamNumChange(num);
  },
  //参数
  cansuPop: function() {
    this.setData({
      cansu: !this.data.cansu
    });
  },
  teamNumChange: function(num) {

    var list = this.data.teamSpecList;
    var teamGoodsinfoList = this.data.teamGoodsinfoList;

    for (var j = 0; j < teamGoodsinfoList.length; j++) {
      teamGoodsinfoList[j].TeamNum = num; //几人团
      var teamgoodslist = teamGoodsinfoList[j].TeamBuyGoodsList;
      for (var i = 0; i < teamgoodslist.length; i++) {
        if (teamgoodslist[i].Num == num) {
          teamGoodsinfoList[j].TeamBuyCurrentPrice = teamgoodslist[i].Price;
          break;
        }
      }
    }

    //按价格高低排升序
    teamGoodsinfoList.sort(function(a, b) {
      var ai = parseFloat(a.TeamBuyCurrentPrice);
      var bi = parseFloat(b.TeamBuyCurrentPrice);
      if (ai > bi) {
        return 1;
      } else if (ai < bi) {
        return -1;
      } else {
        return 0;
      }
    });

    //默认选中显示价格的规格
    var teamGoodsinfo = teamGoodsinfoList[0];
    var specstr = teamGoodsinfo.SpecID;
    var resultSpec = '';
    if (specstr != null && specstr != "") {
      var specarr = specstr.split(',');
      var _specArr = [];
      for (var i = 0, len = list.length; i < len; ++i) {
        for (var j = 0, length = list[i].length; j < length; ++j) {
          var index = specarr.indexOf(list[i][j].ID + "");
          if (index > -1) {
            list[i][j].IsChecked = true;
            _specArr.push(list[i][j].SpecValue);
            var pid = list[i][j].ParentID;
            teamselectIndex[pid] = list[i][j].ID;

          } else {
            list[i][j].IsChecked = false;
          }
        }
      }
      if (_specArr != null && _specArr.length > 0) {
        resultSpec = _specArr.join('-');
      }
    }

    this.setData({

      teamNum: num,
      teamGoodsinfoList: teamGoodsinfoList,
      buyType: 0,
      teamGoodsinfo: teamGoodsinfo,
      _teamspechtml: resultSpec,
      teamSpecList: list,
    });
  },
  changetab: function(e) {
    var id = e.currentTarget.id;
    var tab = this.data.tab;
    var len = tab.length;
    for (var i = 0; i < len; i++) {
      if (tab[i].id == id) {
        if (id == 1 && PageIndex == 1) {

        }
        tab[i].selected = true;
      } else {
        tab[i].selected = false;
      }
    }
    this.setData({
      tab: tab
    });
  },
  //发起拼单
  faqipt: function() {
    this.setData({
      faqiptin: !this.data.faqiptin
    });
  },
  sharePop: function() {
    this.setData({
      sharepopin: !this.data.sharepopin
    });
  },
  sharePopk: function(e) {
    var title = e.currentTarget.dataset.title;
    var content = e.currentTarget.dataset.content;
    this.setData({
      sharepopkin: !this.data.sharepopkin,
      activitytitle: title,
      activitycontent: content,
    });
  },
  selectGg: function(e) {
    this.setData({
      popin: !this.data.popin
    });
  },
  moreBtn: function() {

    this.setData({
      morebtn: true
    });

  },
  sharePopky: function() {
    this.setData({
      morebtn: false
    });
  },

  loadMoreTeam: function() {

    this.setData({
      PageIndexTeam: 2
    });
    var i = 0;

    var that = this;
    var datas = {
      "CustID": app.globalData.custID,
      "ProductID": that.data.productId,
      "UnionStoreID": that.data.shopID,
      "PageIndex": PageIndexTeam,
      "PageSize": PageSizeTeam
    };
    var url = app.globalData.apiurl + "/mobile/api/Product/GetTeamList";
    wx.request({
      url: url,
      data: JSON.stringify(datas),
      method: 'POST',
      header: {
        'X_ManuName': app.globalData.manuName
      },
      success: function(res) {

        if (res.data.code == 1200) {
          var data = res.data.content.Data;

          if (data != null && data != "" && data != "[]") {
            var teamlist = res.data.content.Data;

            var teamTime = setInterval(function() {

              if (teamlist != null && teamlist.length > 0) {
                for (var k = 0; k < teamlist.length; k++) {
                  var endtime = teamlist[k].EndTime;
                  var str = getRTimeNoDay(endtime);
                  if (str != "") {
                    teamlist[k].teamovertime = str;
                  } else {
                    teamlist[k].teamovertime = '00:00:00';
                    //clearInterval(teamTime);
                  }
                }
              }

              that.setData({
                TeamMoreList: data

              });
            }, 1000);

          } else {
            wx.showModal({
              content: "暂无更多拼团",
              showCancel: false,
              confirmText: "确定"
            });
          }

        } else {
          wx.showModal({
            content: "暂无更多拼团",
            showCancel: false,
            confirmText: "确定"
          });
        }
      }
    })
  },

  //一起拼
  togetherBuy: function(e) {
    this.setData({
      morebtn: false,
      pingtuanin: true
    });
    var vo = this.data.vo;
    if (!vo.IsCanBuy) {
      wx.showModal({
        content: "您的等级不能参与此活动",
        showCancel: false,
        confirmText: "确定"
      });
      return;
    }
    var id = e.currentTarget.id;
    var that = this;
    GetTeamById(id, that);
  },
  //一起拼关闭
  closeTogetherBuy: function() {
    this.setData({
      pingtuanin: false,
      joinTeamUser: []
    });
    clearInterval(RTime2);
  },

  //拼团选择规格关闭
  closeInitiateTeamBuy: function(e) {
    var list = this.data.teamSpecList;
    for (var i = 0, len = list.length; i < len; ++i) {
      for (var j = 0, length = list[i].length; j < length; ++j) {
        list[i][j].IsChecked = false;
      }
    }
    this.setData({
      teambuypopin: false,
      faqiptin: false,
      teamGoodsinfo: null,
      teamSpecList: list,
      pingtuanin: false,
      buyType: 0,
    });
  },
  //参与拼团
  joinTeamBuy: function(e) {
    var teamId = e.currentTarget.id;
    var num = e.currentTarget.dataset.teamnumber;
    var teamGoodsinfoList = this.data.teamGoodsinfoList;

    for (var j = 0; j < teamGoodsinfoList.length; j++) {
      teamGoodsinfoList[j].TeamNum = num; //几人团
      var teamgoodslist = teamGoodsinfoList[j].TeamBuyGoodsList;
      for (var i = 0; i < teamgoodslist.length; i++) {
        if (teamgoodslist[i].Num == num) {
          teamGoodsinfoList[j].TeamBuyCurrentPrice = teamgoodslist[i].Price;
          break;
        }
      }
    }

    this.setData({
      teamNum: num,
      pingtuanin: false,
      teambuypopin: !this.data.teambuypopin,
      teamGoodsinfoList: teamGoodsinfoList,
      buyType: 1,
      teamId: teamId,
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.tab[1].selected) {
      if (IsLastPage) {
        wx.showToast({
          title: '已到底',
          duration: 2000
        })
        return false;
      }
      ++PageIndex;
      QueryCommentList(this);
    }
  },

  //减少数量
  onsub: function(e) {
    var num = this.data.num;
    num--;
    if (num < 1) {
      num = 1;
    }
    this.setData({
      num: num
    })
  },
  //增加数量
  onplus: function(e) {
    var num = this.data.num;



    num++;
    this.setData({
      num: num
    })
  },
  onblur: function(e) {
    var num = e.detail.value;
    var r = /^\+?[1-9][0-9]*$/;　　 //正整数  
    var flag = r.test(num);
    if (isNaN(num) || !flag || num < 1) {
      num = 1;
    }
    this.setData({
      num: num
    })
  },
  //选择规格
  onselectspec: function(e) {
    var that = this;
    var id = e.currentTarget.id,
      pid = e.currentTarget.dataset.pid,
      list = that.data.specList;
    selectIndex[pid] = id;

    var arr = [];
    for (var i = 0, len = selectIndex.length; i < len; ++i) {
      if (selectIndex[i])
        arr.push(selectIndex[i]);
    }
    var _specIds = arr.join(',');
    for (var i = 0, len = goodsinfoList.length; i < len; ++i) {
      if (goodsinfoList[i].SpecID == _specIds) {
        goodsinfo = goodsinfoList[i];
      }
    }

    var _specArr = [];
    for (var i = 0, len = list.length; i < len; ++i) {
      for (var j = 0, length = list[i].length; j < length; ++j) {
        if (list[i][j].ParentID == pid && list[i][j].ID != id) {
          list[i][j].IsChecked = false;
        }
        if (list[i][j].ID == id) {
          list[i][j].IsChecked = true;
        }
        for (var k = 0, len2 = arr.length; k < len2; ++k) {
          if (arr[k] == list[i][j].ID) {
            _specArr.push(list[i][j].SpecValue);
          }
        }
      }
    }
    that.setData({
      specList: list,
      _spechtml: _specArr.join('-'),
      goodsinfo: goodsinfo
    })
  },
  //加入购物车
  addtocart: function(e) {
    var num = this.data.num;
    if (!goodsinfo || goodsinfo == undefined) {
      wx.showModal({
        content: "请选择规格",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    if (num <= 0 || num > goodsinfo.StockNum) {
      wx.showModal({
        content: "库存不足",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    var data = {
      ProductID: goodsinfo.ProductID,
      BuyNum: num,
      GoodsID: goodsinfo.GoodsID,
      CustID: app.globalData.custID,
      UserID: wx.getStorageSync('UserInfo').UserID,
      ShopId: this.data.shopID
      
    };
    var that = this;
    var typeid = e.currentTarget.dataset.type;
    var url = app.globalData.apiurl + "/mobile/api/ShopCart/InsertShopCart";
    if (typeid == 1) { //立即购买

      url = app.globalData.apiurl + '/mobile/api/ShopCart/BuyNow';
    }
    wx.request({
      url: url,
      data: JSON.stringify(data),
      method: 'POST',
      header: {
        'X_ManuName': app.globalData.manuName
      },
      success: function(res) {
        if (res.data.code == 1200) {
          if (typeid == 1) { //立即购买
            var cart = res.data.content;
            if (cart) {
              var clist = [];
              clist.push(cart);
              //将购物车选中项缓存起来
              wx.setStorageSync('Winmobi4MallSelectedShopCart', clist);
              wx.navigateTo({
                url: '/pages/submitOrder/submitOrder'
              })
            } else {
              wx.showModal({
                content: '操作失败',
                showCancel: false,
                confirmText: "确定"
              })
            }
          } else {
            that.setData({
              popin: false
            });
            wx.showToast({
              title: '操作成功',
              icon: 'success',
              duration: 2000
            })
          }
        } else {
          wx.showModal({
            content: res.data.msg,
            showCancel: false,
            confirmText: "确定"
          })
        }
      }
    })
  },
  //购物车
  gocart: function(e) {
    wx.switchTab({
      url: '/pages/cart/cart'
    })
  },
  //拼团选择规格
  onselectspecteam: function(e) {
    var that = this;
    var id = e.currentTarget.id,
      pid = e.currentTarget.dataset.pid,
      list = that.data.teamSpecList,
      teamGoodsinfoList = that.data.teamGoodsinfoList;
    teamselectIndex[pid] = id

    var arr = [];
    for (var i = 0, len = teamselectIndex.length; i < len; ++i) {
      if (teamselectIndex[i])
        arr.push(teamselectIndex[i]);
    }
    var teamgoodsinfo = null;
    var _specIds = arr.join(',');
    for (var i = 0, len = teamGoodsinfoList.length; i < len; ++i) {
      if (teamGoodsinfoList[i].SpecID == _specIds) {
        teamgoodsinfo = teamGoodsinfoList[i];
      }
    }

    var _specArr = [];
    for (var i = 0, len = list.length; i < len; ++i) {
      for (var j = 0, length = list[i].length; j < length; ++j) {
        if (list[i][j].ParentID == pid && list[i][j].ID != id) {
          list[i][j].IsChecked = false;
        }
        if (list[i][j].ID == id) {
          list[i][j].IsChecked = true;
        }
        for (var k = 0, len2 = arr.length; k < len2; ++k) {
          if (arr[k] == list[i][j].ID) {
            _specArr.push(list[i][j].SpecValue);
          }
        }
      }
    }
    that.setData({
      teamSpecList: list,
      _teamspechtml: _specArr.join('-'),
      teamGoodsinfo: teamgoodsinfo
    })
  },
  //减少数量
  onteamsub: function(e) {
    var num = this.data.teamBuyNum;
    num--;
    if (num < 1) {
      num = 1;
    }
    this.setData({
      teamBuyNum: num
    })
  },
  //增加数量
  onteamplus: function(e) {
    var num = this.data.teamBuyNum;
    var maxnum = this.data.MaxNum;
    if (maxnum > 0 && num >= maxnum) {
      var msg = "每次最多购买" + maxnum + "件";
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
      return;
    }
    num++;
    this.setData({
      teamBuyNum: num
    })
  },
  onteamblur: function(e) {
    var num = e.detail.value;
    var r = /^\+?[1-9][0-9]*$/;　　 //正整数  
    var flag = r.test(num);
    if (isNaN(num) || !flag || num < 1) {
      num = 1;
    }
    var maxnum = this.data.MaxNum;
    if (maxnum > 0 && num >= maxnum) {
      var msg = "每次最多购买" + maxnum + "件";
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
      num = 1;
    }
    this.setData({
      teamBuyNum: num
    })
  },
  //拼团立即购买
  teamBuyNow: function(e) {
    var buyNum = this.data.teamBuyNum;
    var teamGoodsinfo = this.data.teamGoodsinfo;
    var buyType = this.data.buyType;

    if (!teamGoodsinfo || teamGoodsinfo == undefined) {
      wx.showModal({
        content: "请选择规格",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }
    if (buyNum <= 0 || buyNum > teamGoodsinfo.StockNum) {
      wx.showModal({
        content: "库存不足",
        showCancel: false,
        confirmText: "确定"
      })
      return;
    }

    var Product = {
      ProductID: teamGoodsinfo.ProductID,
      BuyNum: buyNum,
      GoodsID: teamGoodsinfo.GoodsID,
      CustID: app.globalData.custID,
      UserID: wx.getStorageSync('UserInfo').UserID,
      ShopId: this.data.shopID,
      TeamId: this.data.teamId,
      TeamNum: this.data.teamNum,
      Type: buyType,
      ActivityID: this.data.ActivityID
    };
    var plist=new Array();
    plist.push(Product);
    //将购物车选中项缓存起来
    wx.setStorageSync('Winmobi4MallTeamBuyProduct', JSON.stringify(plist));
    wx.navigateTo({
      url: '/pages/teamSubmitOrder/teamSubmitOrder'
    })
  }
})

//加载数据
function loadDetail(that) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/Product/GetTeamProductDetail',
    data: {
      custId: app.globalData.custID,
      productId: that.data.productId,
      userId: wx.getStorageSync('UserInfo').UserID,
      unionShopID: that.data.shopID
    },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {
      wx.hideLoading();
      if (res.data.code == 1200) {
        var result = res.data.content;
        if (result.Activitys.length <= 0) {
          wx.showToast({
            title: '此拼团已失效',
            icon: 'none',
            duration: 4000
          })
        }
        goodsinfoList = result.GoodsInfoList;
        selectIndex = [];
        goodsinfo = null;
        var like = false;
        if (result.Like) {
          like = true;
        }
        if (result.ProductDetail.Detail) {
          wxParse.wxParse('content', 'html', result.ProductDetail.Detail, that, 5)
        }
        if (result.ProductDetail.Parameter) {
          wxParse.wxParse('content2', 'html', result.ProductDetail.Parameter, that, 5)
        }

        var teamGoodsinfoList = [];
        for (var i = 0; i < result.GoodsInfoList.length; i++) {
          if (result.GoodsInfoList[i].IsTeamBuyEnable) {
            teamGoodsinfoList.push(result.GoodsInfoList[i]);
          }
        }

        //活动结束时间倒计时
        var RTime = setInterval(function() {
          var str = getRTime(result.TeamBuyViewModel.TeamBuyActivity.EndDt);
          if (str != "") {
            var arr = str.split(',');
            that.setData({
              activityOverDay: arr[0],
              activityOverHour: arr[1],
              activityOverMinute: arr[2],
              activityOverSecond: arr[3],
            });
          } else {
            clearInterval(RTime);
            that.setData({
              activityOverDay: "00",
              activityOverHour: "00",
              activityOverMinute: "00",
              activityOverSecond: "00",
            });
          }
        }, 1000);

        //默认选中第一个
        if (goodsinfoList != null && goodsinfoList.length > 0) {
          var list = result.SpecList;
          goodsinfo = goodsinfoList[0];

          var specstr = goodsinfo.SpecID;
          var resultSpec = '';
          if (specstr != null && specstr != "") {
            var specarr = specstr.split(',');
            var _specArr = [];
            for (var i = 0, lenI = list.length; i < lenI; ++i) {
              for (var j = 0, lengthJ = list[i].length; j < lengthJ; ++j) {
                var index = specarr.indexOf(list[i][j].ID + "");
                if (index > -1) {
                  list[i][j].IsChecked = true;
                  _specArr.push(list[i][j].SpecValue);
                  var pid = list[i][j].ParentID;
                  selectIndex[pid] = list[i][j].ID;
                }
              }
            }
            if (_specArr != null && _specArr.length > 0) {
              resultSpec = _specArr.join('-');
            }
          }
        }


        var tl = result.TeamBuyViewModel.TeamBuyPriceList;
        var teamOption = new Array();
        if (tl != null && tl.length > 0) {
          for (var k = 0; k < tl.length; k++) {
            teamOption.push(tl[k].Num);
          }
        }
        that.setData({
          vo: result,
          specList: result.SpecList,
          imgUrls: result.ProductInfo.ProductImgList,
          like: like,
          teamGoodsinfoList: teamGoodsinfoList,
          teamSpecList: result.TeamBuyViewModel.TeamBuySpecList,
          goodsinfo: goodsinfo,
          _spechtml: resultSpec,
          team: teamOption,
          MaxNum: result.TeamBuyViewModel.TeamBuyActivity.MaxNum,
          ActivityID: result.TeamBuyViewModel.TeamBuyActivity.ID
        });
        var teamTime = setInterval(function() {
          var teamlist = result.TeamBuyViewModel.TeamList;
          if (teamlist != null && teamlist.length > 0) {
            for (var k = 0; k < teamlist.length; k++) {

              var endtime = teamlist[k].EndTime;
              var str = getRTimeNoDay(endtime);
              if (str != "") {
                teamlist[k].teamovertime = str;
              } else {
                teamlist[k].teamovertime = '00:00:00';
                //clearInterval(teamTime);
              }
            }
          }
          result.TeamBuyViewModel.TeamList = teamlist;
          that.setData({
            vo: result,
          });
        }, 1000);

        if (that.data.teamId > 0) {
          GetTeamById(that.data.teamId, that);
        }
      } else {
        console.log('加载失败');
      }
    }
  })
}

//根据团id拿到团信息
function GetTeamById(id, that) {
  wx.showLoading({
    title: '加载中...',
    mask: true
  });
  wx.request({
    url: app.globalData.apiurl + '/mobile/api/TeamBuy/GetTeamById',
    data: {
      "custId": app.globalData.custID,
      "unionShopID": that.data.shopID,
      "teamId": id
    },
    method: 'GET',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {
      wx.hideLoading();
      if (res.data.code == 1200 && res.data.content != null) {
        that.setData({
          pingtuanin: true,
          morebtn: false,
          joinTeamUser: res.data.content
        });
        clearInterval(RTime2);
        //活动结束时间倒计时
        RTime2 = setInterval(function() {
          var str = getRTime(res.data.content.EndTime);
          if (str != "") {
            var arr = str.split(',');
            that.setData({
              jointeamOverDay: arr[0],
              jointeamOverHour: arr[1],
              jointeamOverMinute: arr[2],
              jointeamOverSecond: arr[3],
            });
          } else {
            clearInterval(RTime2);
            that.setData({
              jointeamOverDay: "00",
              jointeamOverHour: "00",
              jointeamOverMinute: "00",
              jointeamOverSecond: "00",
            });
          }
        }, 1000);
      } else {
        console.log('加载失败');
      }
    }
  });
}

//收藏
function collect(that) {
  var data = {
    CustID: app.globalData.custID,
    UserID: wx.getStorageSync('UserInfo').UserID,
    ProductID: that.data.productId,
    UnionShopID: that.data.shopID
  };
  var collectUrl = "";
  if (that.data.like) {
    collectUrl = app.globalData.apiurl + "/mobile/api/Collection/CancelCollection";
  } else {
    collectUrl = app.globalData.apiurl + "/mobile/api/Collection/InsertMemberCollection";
  }
  wx.request({
    url: collectUrl,
    data: JSON.stringify(data),
    method: 'POST',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {
      if (res.data.code == 1200) {
        that.setData({
          like: !that.data.like
        });
        wx.showToast({
          title: res.data.content,
          icon: 'success',
          duration: 2000
        })
      } else {
        console.log(res.data.msg);
      }
    }
  })
}

//获取商品评价列表
function QueryCommentList(obj) {


  var url = apiurl + '/mobile/api/Product/GetCommentList';

  wx.request({
    url: url,
    data: {
      "CustId": app.globalData.custID,
      "Id": obj.data.productId,
      "Status": Status,
      "PageIndex": PageIndex,
      "PageSize": PageSize,
      "IsMyComment": 1,
      UnionStoreID: obj.data.shopID
    },
    method: 'GET',
    header: {
      'content-type': 'application/json',
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {

      if (res.data.content == null) {
        obj.setData({
          nocomment: false
        })
        return false;
      }
      var dlist = obj.data.CommentList;
      var d = res.data.content.Data;
      for (var i = 0; i < d.length; i++) {
        dlist.push(d[i]);
      }
      obj.setData({
        CommentList: dlist
      })
      if (d.length != PageSize) {
        IsLastPage = true;
        return false;
      }
    },
    fail: function() {
      wx.hideLoading();
      wx.showToast({
        title: '获取评论列表失败',
        duration: 2000
      })
    },
    complete: function() {
      //complete
    }
  })
}

//天时分秒
function getRTime(time) {
  var EndTime = newDate(time); //截止时间
  var NowTime = new Date();

  var t = EndTime.getTime() - NowTime.getTime();
  if (t > 0) {
    var d = Math.floor(t / 1000 / 60 / 60 / 24);
    var h = Math.floor(t % (24 * 3600 * 1000) / 1000 / 60 / 60);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    if (d.toString().length <= 1) {
      d = "0" + d;
    }
    if (h.toString().length <= 1) {
      h = "0" + h;
    }
    if (m.toString().length <= 1) {
      m = "0" + m;
    }
    if (s.toString().length <= 1) {
      s = "0" + s;
    }
    return d + "," + h + "," + m + "," + s;
  } else {
    return "";
  }
}

//正在进行中的团  只要时分秒
function getRTimeNoDay(time) {
  var EndTime = newDate(time); //截止时间
  var NowTime = new Date();

  var t = EndTime.getTime() - NowTime.getTime();
  if (t > 0) {
    var h = Math.floor(t / 1000 / 60 / 60);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    if (h.toString().length <= 1) {
      h = "0" + h;
    }
    if (m.toString().length <= 1) {
      m = "0" + m;
    }
    if (s.toString().length <= 1) {
      s = "0" + s;
    }
    return h + ":" + m + ":" + s;
  } else {
    return "";
  }
}

//日期转换,兼容苹果安卓
function newDate(strdate) {
  var arr = strdate.split(/[- : \/]/);
  var date = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5]);
  return date;
}

//获取更多拼团数据
function getMoreTeam(that) {
  var datas = {
    "CustID": app.globalData.custID,
    "ProductID": that.data.productId,
    "UnionStoreID": that.data.shopID,
    "PageIndex": PageIndexTeam,
    "PageSize": PageSizeTeam
  };
  var url = app.globalData.apiurl + "/mobile/api/Product/GetTeamList";
  wx.request({
    url: url,
    data: JSON.stringify(datas),
    method: 'POST',
    header: {
      'X_ManuName': app.globalData.manuName
    },
    success: function(res) {

      if (res.data.code == 1200) {
        var data = res.data.content.Data;

        if (data != null && data != "" && data != "[]") {
          var teamTime = setInterval(function() {
            var teamlist = res.data.content.Data;
            if (teamlist != null) that.setData({
              allTeamCount: teamlist.length
            });
            if (teamlist != null && teamlist.length > 2) {
              that.setData({
                hiddenMoreTeam: false

              });
            }

            if (teamlist != null && teamlist.length > 0) {
              for (var k = 0; k < teamlist.length; k++) {
                var endtime = teamlist[k].EndTime;
                var str = getRTimeNoDay(endtime);
                if (str != "") {
                  teamlist[k].teamovertime = str;
                } else {
                  teamlist[k].teamovertime = '00:00:00';
                  //clearInterval(teamTime);
                }
              }
            }
            that.setData({
              TeamMoreList: data

            });
          }, 1000);

        }

      }
    }
  })
}